package util

import (
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"github.com/spf13/viper"
	"log"
	"time"
)

type Claims struct {
	UserID   int64  `json:"user_id"`
	Username string `json:"username"`
	RoleID   int64  `json:"role_id"`
	jwt.RegisteredClaims
}

// GenerateToken
// 生成 JWT Token
func GenerateToken(userID, roleID int64, username string) (string, error) {
	// 设置过期时间 2小时
	expireTime := time.Now().Add(time.Duration(viper.GetInt("jwt.expires")) * time.Second)
	claims := &Claims{
		UserID:   userID,
		Username: username,
		RoleID:   roleID,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expireTime),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			Issuer:    viper.GetString("jwt.issuer"),
		},
	}
	//  生成 token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(viper.GetString("jwt.secret")))
}

// parseToken
// 解析token
func ParseToken(tokenString string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(viper.GetString("jwt.secret")), nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		return claims, nil
	}
	return nil, err
}

// GetUserInfo
func GetUserInfo(c *gin.Context) *Claims {
	claims, exists := c.Get("claims")
	if !exists {
		return nil
	}
	return claims.(*Claims)
}

// RefreshExpTime
// 刷新token
func RefreshExpTime(oldTokenStr string) (string, error) {
	token, err := jwt.ParseWithClaims(oldTokenStr, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(viper.GetString("jwt.secret")), nil
	})
	if err != nil || !token.Valid {
		log.Fatalln("token验证失败", err.Error())
		return "", err
	}
	// 延长有效期
	claims := token.Claims.(*Claims)
	claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Hour * 2))
	claims.IssuedAt = jwt.NewNumericDate(time.Now())
	// 生成新的token
	newToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return newToken.SignedString([]byte(viper.GetString("jwt.secret")))
}
